package www.ld.com.controller;

import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import www.ld.com.core.group.InsertGroup;
import www.ld.com.core.group.UpdateGroup;
import www.ld.com.domain.R;
import www.ld.com.domain.attr.pojo.AttrPO;
import www.ld.com.domain.attr.query.AttrQuery;
import www.ld.com.domain.attr.vo.AttrVO;
import www.ld.com.domain.attr.vo.InAttrVO;
import www.ld.com.domain.attr.vo.OutAttrVO;
import www.ld.com.domain.vo.PageRestVO;
import www.ld.com.service.AttrService;
import www.ld.com.utils.PageUtils;

import javax.annotation.Resource;

@Api(tags = "属性管理")
@RestController
@RequestMapping("/attr")
public class AttrController {
    @Resource
    private AttrService attrService;

    @GetMapping
    @ApiOperation(value = "属性列表")
    @PreAuthorize("hasAuthority('pms:attr:select')  or  hasAuthority('pms:attr-group:relation') ")
    public R<PageRestVO<AttrVO>> pageList(AttrQuery attrQuery) {
        PageRestVO pageRestVO = PageUtils.copyPageVO(attrService.pageAttrByAttrQuery(attrQuery), AttrVO.class);
        return R.ok(pageRestVO);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "获取属性详情")
    @PreAuthorize("hasAuthority('pms:attr:select')")
    public R<OutAttrVO> getAttrById(@PathVariable(value = "id", required = true) String id) {
        AttrPO attrGroupPO = attrService.getAttrPOById(id);
        return R.ok(BeanUtil.toBean(attrGroupPO, OutAttrVO.class));
    }

    @ApiOperation(value = "新增属性")
    @PostMapping
    @PreAuthorize("hasAuthority('pms:attr:create')")
    public R save(@RequestBody @Validated(value = {InsertGroup.class}) InAttrVO inAttrVO) {
        attrService.saveAttrPO(BeanUtil.toBean(inAttrVO, AttrPO.class));
        return R.ok();
    }

    @ApiOperation(value = "修改属性")
    @PutMapping
    @PreAuthorize("hasAuthority('pms:attr:update')")
    public R update(@RequestBody @Validated(value = {UpdateGroup.class}) InAttrVO inAttrVO) {
        attrService.updateAttrPO(BeanUtil.toBean(inAttrVO, AttrPO.class));
        return R.ok();
    }

    @ApiOperation(value = "删除属性")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('pms:attr:delete')")
    public R delete(@PathVariable(value = "id", required = true) String id) {
        attrService.deleteAttrById(id);
        return R.ok();
    }
}
